package com.jnu.myfirstapplication;


import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.jnu.myfirstapplication.data.HttpDataLoader;
import com.jnu.myfirstapplication.data.ShopLocation;
import com.tencent.tencentmap.mapsdk.maps.CameraUpdate;
import com.tencent.tencentmap.mapsdk.maps.CameraUpdateFactory;
import com.tencent.tencentmap.mapsdk.maps.MapView;
import com.tencent.tencentmap.mapsdk.maps.TencentMap;
import com.tencent.tencentmap.mapsdk.maps.TextureMapView;
import com.tencent.tencentmap.mapsdk.maps.UiSettings;
import com.tencent.tencentmap.mapsdk.maps.model.AlphaAnimation;
import com.tencent.tencentmap.mapsdk.maps.model.Animation;
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptor;
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptorFactory;
import com.tencent.tencentmap.mapsdk.maps.model.CameraPosition;
import com.tencent.tencentmap.mapsdk.maps.model.LatLng;
import com.tencent.tencentmap.mapsdk.maps.model.Marker;
import com.tencent.tencentmap.mapsdk.maps.model.MarkerOptions;

import java.lang.ref.WeakReference;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MapFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MapFragment extends Fragment {
    private TextureMapView mapView;
    private Marker marker;
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    break;
                default:
                    break;
            }
        }
    };

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER

    // TODO: Rename and change types of parameters

    public MapFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment MapFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MapFragment newInstance() {
        MapFragment fragment = new MapFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onStart() {
        // TODO Auto-generated method stub
        super.onStart();

        mapView.onStart();
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        mapView.setVisibility(View.VISIBLE);
        mapView.onResume();
    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        mapView.onPause();
    }

    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        mapView.onStop();
    }


    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mapView.onDestroy();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_map, container, false);
        mapView = rootView.findViewById(R.id.map);
        TencentMap map = mapView.getMap();
        UiSettings mapUiSettings = map.getUiSettings();
        CameraUpdate cameraSigma =
                CameraUpdateFactory.newCameraPosition(new CameraPosition(
                        new LatLng(22.249837, 113.537022), //新的中心点坐标  x为latitude，y为longitude
                        15,  //新的缩放级别
                        0, //俯仰角 0~45° (垂直地图时为0)
                        0)); //偏航角 0~360° (正北方为0)
        //移动地图
        map.moveCamera(cameraSigma);

        map.setOnMarkerDragListener(new TencentMap.OnMarkerDragListener() {
            @Override
            public void onMarkerDragStart(Marker marker) {
                //当前手指按住Marker拖拽开始
            }

            @Override

            public void onMarkerDrag(Marker marker) {
                //当前手指按住Marker拖拽中
            }

            @Override
            public void onMarkerDragEnd(Marker marker) {
                Toast.makeText(getContext().getApplicationContext(), ("经纬度坐标：" + marker.getPosition()), Toast.LENGTH_LONG).show();
                //当前手指按住Marker拖拽结束
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String shopJsonData = HttpDataLoader.getHttpData("http://file.nidama.net/class/mobile_develop/data/bookstore2022.json");
                    HttpDataLoader dataLoader = new HttpDataLoader();
                    List<ShopLocation> locations = dataLoader.ParseJsonData(shopJsonData);
                    Looper.prepare();

                    handler.post(() -> {
                        AddMarkersOnMap(locations);
                    });
//                    handler.post(new Runnable() {
//                        @Override
//                        public void run() {
//                            AddMarkersOnMap(locations);
//                        }
//                    });
//                    MapFragment.this.getActivity().runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            AddMarkersOnMap(locations);
//                        }
//                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
        //marker.setClickable(true);
//        marker.setDraggable(true);
//        marker = map.addMarker(new MarkerOptions(position));
//        Animation animation = new AlphaAnimation(0.7f, 0f);
//        animation.setDuration(2000);
//        marker.setAnimation(animation);
//        marker.startAnimation();

        return rootView;
    }

    private void AddMarkersOnMap(List<ShopLocation> locations) {
        TencentMap map = mapView.getMap();
        BitmapDescriptor custom = BitmapDescriptorFactory.fromResource(R.drawable.jinan);
        for (ShopLocation shop : locations) {
            LatLng position = new LatLng(shop.getLatitude(), shop.getLongitude());
            marker = map.addMarker(new MarkerOptions(position)
                    .icon(custom)
                    .alpha(0.6f)
                    .flat(true)
                    .clockwise(false)
                    .rotation(30)
                    .snippet("地址：香洲区前山路206号")
                    .draggable(true));
            marker.setTitle("暨南大学珠海校区");
        }
    }

}